<template>
  <div>
    <div class="herdertop">
      <img src="../../assets/top.png" alt="" class="topImg" />
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>服务管理</el-breadcrumb-item>
        <el-breadcrumb-item>报事报修类型管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="center" style="padding-top: 0px;">
      <div class="hander">报事报修类型管理</div>
      <div class="orderList">
        <div class="entirety">
          <div class="search">
            <!--  账号状态搜索信息 -->
            <div class="demo-input-suffix">
              服务类型名称
              <el-input
                style=" width: 61%;"
                v-model="serviceName"
                placeholder="输入服务类型名称"
                clearable
              ></el-input>
            </div>
            <div class="news">
              <el-button
                style="background-color:#fd804c;color: #fff;"
                @click="isDialog('新增')"
                >新增
              </el-button>

              <el-dialog :title="msg" :visible.sync="dialogFormVisible">
                <el-form
                  ref="form"
                  :model="form"
                  status-icon
                  label-width="130px"
                  label-position
                  class="demo-ruleForm"
                >
                  <el-form-item
                    label="配置图片:"
                    prop="imgUrl"
                    v-if="msg == '编辑'"
                  >
                    <div>
                      <div style=" float: left;">
                        <img
                          :src="form.serviceIcon"
                          class="avatar"
                          v-if="form.serviceIcon"
                        />
                      </div>
                      <div
                        style="float: left;margin-top:33px; padding-left:15px;"
                      >
                        <el-upload
                          class="avatar-uploader"
                          action="https://api.xstarlife.com/systemapp/upload/singleFileUpload"
                          :headers="{ uploadScene: 'avatar' }"
                          :on-success="handleAvatarSuccess"
                          :show-file-list="false"
                          :before-upload="beforeAvatarUpload"
                        >
                          <div class="change">更换头像</div>
                        </el-upload>
                      </div>
                    </div>
                  </el-form-item>
                  <el-form-item
                    label="配置图片:"
                    prop="imgUrl"
                    v-if="msg == '新增'"
                  >
                    <el-upload
                      class="avatar-uploader"
                      action="https://api.xstarlife.com/systemapp/upload/singleFileUpload"
                      :headers="{ uploadScene: 'avatar' }"
                      :on-success="handleAvatarSuccess"
                      :show-file-list="false"
                      :before-upload="beforeAvatarUpload"
                    >
                      <img
                        v-if="serviceIcon"
                        :src="serviceIcon"
                        class="avatar"
                      />
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-form-item>
                  <el-form-item label="服务类型名称:" prop="serviceName">
                    <el-input
                      style="width: 50%; margin-bottom: 10px; margin-left: 10px"
                      v-model="form.serviceName"
                      maxlength="10"
                      show-word-limit
                      placeholder="输入服务类型名称"
                    ></el-input>
                  </el-form-item>

                  <el-form-item label="显示位置:" prop="sort">
                    <el-select
                      clearable
                      v-model="form.sort"
                      placeholder="请选择"
                      style="margin: 10px"
                    >
                      <el-option
                        v-for="(item, index) in PltfmTypeData"
                        :key="index"
                        :label="item"
                        :value="item"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item
                    label="ERP一级分类:"
                    prop="primaryClassificationCode"
                  >
                    <el-select
                      clearable
                      v-model="form.templateDifId"
                      placeholder="请选择"
                      style="margin: 10px"
                      @change="onSelectedCityList($event)"
                    >
                      <el-option
                        v-for="item in WorkOrderServiceList"
                        :key="item.templateDifId"
                        :label="item.aliasName"
                        :value="item.templateDifId"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item
                    label="ERP二级分类:"
                    prop="secondaryClassificationCode"
                  >
                    <el-select
                      clearable
                      v-model="form.businessCode"
                      placeholder="请选择"
                      style="margin: 10px"
                    >
                      <el-option
                        v-for="item in secondaryClassificationVOList"
                        :key="item.businessCode"
                        :label="item.businessName"
                        :value="item.businessCode"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item label="社区选择:">
                    <el-checkbox
                      v-model="checkAll"
                      @change="handleCheckAllChange"
                      >全选</el-checkbox
                    >
                    <el-tree
                      :data="treeData"
                      ref="treeData"
                      show-checkbox
                      default-expand-all
                      @check="checkClick"
                      node-key="id"
                      :props="defaultProps"
                    >
                    </el-tree>
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="dialogFormVisible = false"
                    >取 消</el-button
                  >
                  <el-button
                    style="background-color:#fd804c;color: #fff;"
                    @click="isSubmit"
                    >确 定</el-button
                  >
                </div>
              </el-dialog>
            </div>
          </div>
          <div class="demo-input-suffix" style="margin:10px;">
            <el-button
              style="background-color:#fd804c;color: #fff;"
              @click.native.prevent="isSelect"
              >查询</el-button
            >
            <el-button type="warning" @click.native.prevent="isEmpty"
              >清空</el-button
            >
          </div>
        </div>
        <!--  报事报修类型管理列表栏位-->
        <div
          class="entirety"
          v-loading="isLoading"
          element-loading-text="数据加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-custom-class="loading_color"
        >
          <div class="footer">
            <el-table :data="tableData" style="width: 100%">
              <el-table-column prop="serviceIcon" label="图片">
                <template slot-scope="scope">
                  <el-image
                    style="width: 70px; height: 30px"
                    :src="scope.row.serviceIcon"
                    :preview-src-list="[scope.row.serviceIcon]"
                    :fit="'contain'"
                  ></el-image>
                </template>
              </el-table-column>

              <el-table-column prop="serviceName" label="服务类型名称	">
                <template slot-scope="scope">
                  <div>
                    {{ scope.row.serviceName }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="primaryClassification" label="ERP一级分类">
                <template slot-scope="scope">
                  <div>
                    {{ scope.row.primaryClassification }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="secondaryClassification"
                label="ERP二级分类"
              >
                <template slot-scope="scope">
                  <div>
                    {{ scope.row.secondaryClassification }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="sort" label="展示位置">
                <template slot-scope="scope">
                  <div>
                    {{ scope.row.sort }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="useCommunityName" label="展示社区">
                <template slot-scope="scope">
                  <div>
                    {{ scope.row.useCommunityName }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                  <el-button
                    @click="isDialog('编辑', scope.row)"
                    style="color: #fc9e76;"
                    type="text"
                    size="small"
                  >
                    编辑
                  </el-button>
                  <el-button
                    @click="isDel(scope.row.id)"
                    style="color: #fc9e76;"
                    type="text"
                    size="small"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="block">
              <div class="left"></div>
              <div class="right">
                <el-pagination
                  layout="total, sizes, prev, pager, next, jumper"
                  class="page"
                  @size-change="sizeChangeHandle"
                  @current-change="currentChangeHandle"
                  :current-page="pageIndex"
                  :page-size="pageSize"
                  :total="total"
                >
                </el-pagination>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      serviceIcon: "",
      pageIndex: 1,
      pageSize: 20,
      total: 0,
      id: "",
      business: [],
      PltfmTypeData: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      pageIndex: 1,
      msg: "",
      total: 0,
      serviceName: "",
      isLoading: false,

      dialogFormVisible: false,
      tableData: [],
      checkAll: false,
      regionCommunityList: [],
      treeData: [],
      // children和label 与接口字段保持一致
      defaultProps: {
        children: "pmcCommunities",
        label: "label"
      },

      form: {
        communityCodes: [],
        templateDifId: "",
        businessCode: "",
        serviceIcon: "",
        serviceId: 0,
        serviceName: "",
        sort: 0
      },
      // rules: {
      //   serviceName: [{ max: 10, message: "长度10个字符", trigger: "change" }],
      //   sort: [{ required: true, message: "请选择适用端:", trigger: "change" }],
      //   serviceIcon: [
      //     { required: true, message: "请选择图片:", trigger: "change" }
      //   ],
      //   primaryClassificationCode: [
      //     { required: true, message: "请选择ERP一级分类:", trigger: "change" }
      //   ],
      //   secondaryClassificationCode: [
      //     { required: true, message: "请选择ERP二级分类:", trigger: "change" }
      //   ]
      // },
      cityAndCommunityList: [],
      refCodeAndBusinessCode: [],
      WorkOrderServiceList: [],
      secondaryClassificationVOList: []
    };
  },
  activated() {
    this.DetailByPage();
    this.getCityAndCommunityInfo();
    this.isEmpty();
    this.getErpWorkOrderService();
  },
  methods: {
    isSelect() {
      (this.pageIndex = 1), (this.pageSize = 20), this.DetailByPage();
    },
    isEmpty() {
      (this.serviceName = ""),
        (this.pageIndex = 1),
        (this.pageSize = 20),
        this.DetailByPage();
    },
    handleCheckAllChange(val) {
      if (this.checkAll) {
        this.$refs.treeData.setCheckedNodes(this.treeData);

        const result = [];

        this.$refs.treeData.data.forEach(item => {
          const { id, pmcCommunities = [] } = item;
          pmcCommunities.forEach(itm => {
            result.push(itm.id);
          });
        });
        //console.log("result,,,,,,,", result);

        this.form.AllData = result;
        //console.log("result,,,,,,,", this.AllData);
      } else {
        this.$refs.treeData.setCheckedKeys([]);
        this.form.AllData = [];
      }
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只支持JPG/JPEG/png格式");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess(res) {
      if (this.msg == "编辑") {
        this.form.serviceIcon = res.data;
      } else {
        this.serviceIcon = res.data;
      }
    },

    onSelectedCityList(e) {
      //console.log(" this.couponNo,,,e,,,33", e);
      // this.couponApplyAreaInsertDTOS[index].businessAreaCode = "";
      const cityData = this.WorkOrderServiceList.find(item => {
        this.form.templateDifId = e;

        if (item.templateDifId == this.form.templateDifId) {
          return item.templateDifId == e; //筛选出匹配数据
        }
      });

      this.secondaryClassificationVOList =
        cityData.secondaryClassificationVOList;
    },
    isDialog(type, data) {
      //console.log("data,,,,,,,,", data);
      this.msg = type;

      if (type == "新增") {
        (this.form = {}), (this.dialogFormVisible = true);
      } else {
        //console.log("data,,,,,sdds,,,", data.serviceId);
        this.form = data;
        this.form.serviceId = data.id;
        this.form.serviceIcon = data.serviceIcon;
        this.form.templateDifId = data.templateDifId;
        this.form.businessCode = data.businessCode;
        this.dialogFormVisible = true;
      }
    },
    //根据id删除
    isDel(id) {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: "/orderapp/mgr/workOrder/deleteWorkOrderService/" + id,
            method: "DELETE"
          })
            .then(res => {
              if (res.success == 1) {
                this.$message.success("删除成功");
                this.DetailByPage();
              }
            })
            .catch(() => {
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //分页获取优惠券模板列表接口调用
    DetailByPage() {
      this.isLoading = true;

      this.$http({
        url: `/orderapp/mgr/workOrder/getWorkOrderServiceByPage`,
        method: "POST",
        data: {
          serviceName: this.serviceName,
          size: this.pageSize,
          page: this.pageIndex
        }
      })
        .then(res => {
          this.tableData = res.data.list;
          this.isLoading = false;
          this.total = parseInt(res.data.total);
        })
        .catch(_ => {
          this.isLoading = false;
        });
    },
    //分页获取优惠券模板列表接口调用
    getErpWorkOrderService() {
      this.$http({
        url: `/orderapp/mgr/workOrder/getErpWorkOrderService`,
        method: "GET"
      }).then(res => {
        if (res.success == 1) {
          this.WorkOrderServiceList = res.data;
        }
      });
    },

    //社区
    getCityAndCommunityInfo() {
      this.$http({
        url: `/pmcapp/mgr/regions/getCityAndCommunityInfo`,
        method: "GET"
      }).then(res => {
        if (res.success == 1) {
          res.data.map(item => {
            item.label = item.subRgName;
            item.pmcCommunities.map(item1 => {
              item1.id = item1.communityCode;
              item1.label = item1.communityName;
            });
          });
          this.treeData = res.data;
        }
      });
    },
    checkClick() {
      const b = [].concat(
        this.$refs.treeData.getHalfCheckedKeys(),
        this.$refs.treeData.getCheckedKeys()
      );
      const refCodeAndBusinessCode = [];

      this.treeData.forEach(item => {
        item.pmcCommunities.forEach(itm => {
          const fig = b.includes(itm.id);

          if (fig) {
            refCodeAndBusinessCode.push(itm.id);
          }
        });
      });

      this.form.communityCodes = refCodeAndBusinessCode;
    },

    isSubmit() {
      //console.log(" this.form.serviceId,,,,,", this.form.serviceId);
      if (this.msg == "新增") {
        if (this.serviceIcon !== "") {
          this.$http({
            url: `/orderapp/mgr/workOrder/addWorkOrderService`,
            method: "POST",
            data: {
              communityCodes: this.form.communityCodes,
              primaryClassificationCode: this.form.templateDifId,
              secondaryClassificationCode: this.form.businessCode,
              serviceIcon: this.serviceIcon,
              serviceName: this.form.serviceName,
              sort: this.form.sort
            }
          })
            .then(res => {
              if (res.success == 1) {
                this.$message.success("添加成功");
                this.DetailByPage();
              } else {
                this.$message.error(res.errorMsg);
              }
              this.dialogFormVisible = false;
            })
            .catch(() => {
              this.$message.error("添加失败");
            });
        } else {
          this.$message.error("图片不能为空");
        }
      } else {
        //console.log("this.form.serviceId,,,,,", this.form.serviceId);
        this.$http({
          url: `/orderapp/mgr/workOrder/modifyWorkOrderService`,
          method: "PUT",
          data: {
            communityCodes: this.form.communityCodes,
            primaryClassificationCode: this.form.templateDifId,
            secondaryClassificationCode: this.form.businessCode,
            serviceIcon: this.form.serviceIcon || this.serviceIcon,
            serviceId: this.form.serviceId,
            serviceName: this.form.serviceName,
            sort: this.form.sort
          }
        })
          .then(res => {
            if (res.success == 1) {
              this.$message.success("修改成功");
              this.dialogFormVisible = false;

              this.DetailByPage();
            } else {
              this.$message.error(res.errorMsg);
              this.dialogFormVisible = false;
            }
          })
          .catch(() => {
            this.$message.error("修改失败");
            this.dialogFormVisible = false;
          });
      }
    },

    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;

      this.DetailByPage();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;

      this.DetailByPage();
    }
  }
};
</script>
<style scoped lang="scss">
.block {
  width: 100%;
  height: 70px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding: 0 10px 0 10px;
}
.left {
  font-size: 15px;
}
/deep/ .el-loading-spinner i {
  color: #fc9e76;
}
/deep/ .el-loading-spinner .el-loading-text {
  color: #fc9e76;
  margin: 3px 0;
  font-size: 14px;
}
/deep/ .el-upload {
  border: 1px dashed #999999;
}
.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 108px;
  height: 108px;
  display: block;
}
.hander {
  width: 100%;
  height: 50px;
  line-height: 50px;
  font-size: 20px;
  font-weight: 900;
}
.news {
  margin-left: 4%;
}
.orderList {
  background-color: #ebeef1;
  padding-right: 40px;
  padding-top: 1px;
  padding-bottom: 1px;
  display: block;
  font-size: 16px;
  border-radius: 20px;
  list-style-type: none;
}
.entirety {
  width: 100%;
  margin: 10px;
  height: 100%;
  padding: 10px;
  background-color: #fff;
  border-radius: 10px;
  display: flex;
  padding-left: 10px;
  .basic {
    font-size: 18px;
    font-weight: 900;
    margin-top: 2%;
    margin-bottom: 1%;
    margin-left: 1%;
  }
}
.footer {
  width: 100%;
  display: flex;
  overflow: hidden;
  flex-direction: column;
}
.search {
  margin-bottom: 15px;
  padding-top: 10px;
}
.page {
  margin-top: 15px;
}
.news {
  margin-left: 8%;
}
.overall {
  width: 100%;
  height: auto;
  display: flex;

  justify-content: space-between;
  margin-top: 3%;
  .left {
    width: 20%;
    height: auto;
  }
  .right {
    width: 80%;
    height: auto;
  }
}
.demo-input-suffix {
  margin-left: 1%;
}
.select {
  width: 65%;
  height: auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .dialog-footer,
  .choice {
    margin-left: 2%;
  }
}
.herdertop {
  height: 8vh;
  display: flex;
  align-items: center;
  padding: 0 20px;
  box-sizing: border-box;
}
.topImg {
  margin-right: 20px;
}
/deep/ .itemClass .el-form-item__content {
  width: 350px;
}
.userSearch {
  display: flex;
  /deep/ .el-input__inner {
    box-sizing: border-box;
    height: 40px;
    border-radius: 0;
    width: 132px;
    border: 1px solid #dcdfe6;
  }
  /deep/ .el-icon-arrow-up:before {
    position: relative;
    top: -4px;
  }
  /deep/ .el-button {
    height: 40px;
    border-radius: 0;
    background-color: #fff;
    border: 1px solid #dcdfe6;
    border-left: none;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    position: relative;
    .el-icon-search {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }
  /deep/ .el-input--suffix .el-input__inner {
    border-right: none;
  }
  /deep/ .el-input--suffix .el-input__inner {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
  }
}
.selects {
  width: 55%;
  height: auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .dialog-footer,
  .choice {
    margin-left: 2%;
  }
}

/deep/ .but {
  background: #fd7097;
  color: #fff;
  margin-bottom: 1%;
}
</style>
